package com.webridge.wpmtest.util;

import java.util.Date;

import org.apache.log4j.Logger;


import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTHashSet;
import wt.fc.collections.WTKeyedHashMap;
import wt.fc.collections.WTKeyedMap;
import wt.fc.collections.WTSet;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.maturity.MaturityBaseline;
import wt.maturity.MaturityHelper;
import wt.maturity.PromotionNotice;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartMasterIdentity;
import wt.pds.StatementSpec;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.WhereExpression;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.baseline.BaselineHelper;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewManageable;
import wt.workflow.definer.WfProcessTemplate;

public class PartTestUtil {

    private static final Logger LOGGER = LogR.getLogger(PartTestUtil.class.getName());
    
    public static WTSet queryAllUnReleasedPartWay1() throws WTException {
        LOGGER.debug("query all UnReleased Part way1,start:" + new Date());
        WTSet set = new WTHashSet();
        String state = "RELEASED";

        QuerySpec querySpec =  new QuerySpec(WTPart.class);

        
        View view = ViewHelper.service.getView("Design");
        ObjectIdentifier objId = PersistenceHelper
                .getObjectIdentifier(view);
        WhereExpression where = new SearchCondition(WTPart.class, ViewManageable.VIEW
                + "." + ObjectReference.KEY, SearchCondition.EQUAL,
                objId);
        querySpec.appendWhere(where,  new int[] { 0 });
        
        if (state != null && !"".equalsIgnoreCase(state)) {
            querySpec.appendAnd();
            querySpec.appendWhere(new SearchCondition(WTPart.class,
                    WTPart.LIFE_CYCLE_STATE, SearchCondition.NOT_EQUAL,
                    state), new int[] { 0 });
        }
        QueryResult qr = PersistenceHelper.manager.find(querySpec);
        qr = new LatestConfigSpec().process(qr);
        while (qr.hasMoreElements()) {
            WTPart part = (WTPart) qr.nextElement();
             LOGGER.debug("query result Part Number:" + part.getNumber());
            set.add(part);
        }
        LOGGER.debug("total:" + set.size());
//        LOGGER.debug("set:" + set);

        LOGGER.debug("query all UnReleased Part way1," + new Date());
        return set;

    }
    
    /**
     * 方式2
     * @return
     * @throws WTException
     */
    public static WTSet queryAllUnReleasedPartWay2() throws WTException {
        LOGGER.debug("query all UnReleased Part way2,start:" + new Date());
        WTSet set = new WTHashSet();

        StatementSpec stmtSpec = new QuerySpec(WTPart.class);

/*        if (state != null && !"".equalsIgnoreCase(state)) {
            querySpec.appendAnd();
            querySpec.appendWhere(new SearchCondition(WTPart.class,
                    WTPart.LIFE_CYCLE_STATE, SearchCondition.NOT_EQUAL,
                    state), new int[] { 0 });
        }*/
        QueryResult qr = PersistenceServerHelper.manager
                .query(stmtSpec);

        while (qr.hasMoreElements()) {
            WTPart part = (WTPart) qr.nextElement();
            // LOGGER.debug("query result Part Number:" + part.getNumber());
            if (part.isLatestIteration())
            {
                if (!"RELEASED".equals(part.getState().getState().toString())) {
                    LOGGER.debug("query result Part Number:" + part.getNumber());
                    set.add(part);
                }
            }

        }
        LOGGER.debug("total:" + set.size());
//        LOGGER.debug("set:" + set);

        LOGGER.debug("query all UnReleased Part way2," + new Date());
        return set;

    }
    
    public void addToPromotionRequest(WTSet set) throws WTException, WTPropertyVetoException{
        long time = System.currentTimeMillis();
        PromotionNotice promotion = PromotionNotice.newPromotionNotice("PN0001-"+time);
        
        MaturityBaseline maturityBaseline = MaturityBaseline.newMaturityBaseline();
        WTContainer container =  WCUtil.getWtContainerByName("computer");
        maturityBaseline.setContainer(container);
        maturityBaseline = (MaturityBaseline) PersistenceHelper.manager.save(maturityBaseline);
        promotion.setConfiguration(maturityBaseline);
        promotion.setContainer(container);

        // folder
        String folderpath = "";
        Folder folder=null;
        if (folder == null) {
            folderpath = "/Default";
//            folder = getFolder(WTContainerRef.newWTContainerRef(container), folderpath);
            folder = FolderHelper.service.getFolder(folderpath, WTContainerRef.newWTContainerRef(container));
        }
        if (folder != null) {
            FolderHelper.assignLocation((FolderEntry) promotion, folder);
        }
        
        promotion.setMaturityState(State.toState("LC150"));     
        promotion = MaturityHelper.service.savePromotionNotice(promotion);
        promotion = (PromotionNotice) PersistenceHelper.manager.refresh(promotion);
        
        MaturityHelper.service.savePromotionNotice(promotion);
        promotion = (PromotionNotice) PersistenceHelper.manager.save(promotion); 
        LOGGER.debug("PN:" + promotion.getName()+","+promotion.getNumber());
        MaturityHelper.service.savePromotionTargets(promotion, set);
        BaselineHelper.service.addToBaseline(set, maturityBaseline);
        promotion = (PromotionNotice) PersistenceHelper.manager.refresh(promotion); 
        MaturityHelper.service.startPromotionProcess(promotion, findWFTemplateByName("Promotion Request Approval Process"));
    
    
    }
    
    public static WfProcessTemplate findWFTemplateByName(String wftemplate) throws WTException
    {
        QuerySpec qs = new QuerySpec(wt.workflow.definer.WfProcessTemplate.class);
        qs.appendWhere(new SearchCondition(wt.workflow.definer.WfProcessTemplate.class, "master>name", "=", wftemplate));
        qs.appendAnd();
        qs.appendWhere(new SearchCondition(wt.workflow.definer.WfProcessTemplate.class, "iterationInfo.latest", "TRUE"));

        QueryResult qr = PersistenceHelper.manager.find(qs);

        if (qr.size() > 0)
        {
            return (WfProcessTemplate)qr.nextElement();
        }

        return null;
    }
    
    
    /**
     * 
     * @throws WTException
     * @throws WTPropertyVetoException
     */
    public static void updatePartName() throws WTException, WTPropertyVetoException {
        LOGGER.debug("updatePartName,start:" + new Date());
        WTSet set = new WTHashSet();
        String state = "RELEASED";

        QuerySpec querySpec =  new QuerySpec(WTPart.class);

        
        View view = ViewHelper.service.getView("Design");
        ObjectIdentifier objId = PersistenceHelper
                .getObjectIdentifier(view);
        WhereExpression where = new SearchCondition(WTPart.class, ViewManageable.VIEW
                + "." + ObjectReference.KEY, SearchCondition.EQUAL,
                objId);
        querySpec.appendWhere(where,  new int[] { 0 });
        
        if (state != null && !"".equalsIgnoreCase(state)) {
            querySpec.appendAnd();
            querySpec.appendWhere(new SearchCondition(WTPart.class,
                    WTPart.LIFE_CYCLE_STATE, SearchCondition.NOT_EQUAL,
                    state), new int[] { 0 });
        }
        QueryResult qr = PersistenceHelper.manager.find(querySpec);
        qr = new LatestConfigSpec().process(qr);
        int i=0;
        while (qr.hasMoreElements()) {
            i++;
            WTPart part = (WTPart) qr.nextElement();
            LOGGER.debug("Part old Name:"+part.getName()+",old Number:" + part.getNumber()+",count:" + i);
             WTPartMaster master = (WTPartMaster) part.getMaster();
             master = WTPartHelper.service.changeWTPartMasterIdentity(master, "AUTO-"+System.currentTimeMillis(),master.getNumber(),  null);
             master = (WTPartMaster) PersistenceHelper.manager.refresh(master);
             LOGGER.debug("Part new Name:"+master.getName()+",new Number:" + master.getNumber());
            set.add(part);
        }
        LOGGER.debug("total:" + set.size());
//        LOGGER.debug("set:" + set);


    }
    
    
    
    
    
    
}
